import jwt
from django.db.models import Q
from .models import UserModel
from rest_framework import viewsets
from .serializers import UserModelSerializers
from rest_framework.views import APIView
from rest_framework.response import Response


from Apps.users.utils.jwt_auth import create_access_token,create_refresh_token
from Apps.users.utils.authenticate import AccessAuthentication
from demo import settings
# Create your views here.


class RegisterView(APIView):
    def post(self, request, *args, **kwargs):
        print(request.data)
        username = request.data.get('username')
        pwd = request.data.get('password')

        UserModel.save(username,pwd)
        return Response({'username': username, 'pwd': pwd})


class LoginView(APIView):
    def post(self,request, *args,**kwargs):
        username = request.data.get('username')
        pwd = request.data.get('password')

        user_object = UserModel.objects.get(Q(username=username) | Q(mobile=username) | Q(email=username))

        if not user_object.check_password(pwd):
            return Response({'code':1000,'error':'用户名或密码错误'})

        access_token = create_access_token({'id':user_object.id, 'username':user_object.username})
        refresh_token = create_refresh_token({'id':user_object.id, 'username':user_object.username})
        return Response({'code': 1001, 'access_token': access_token, 'refresh_token': refresh_token})


class RefreshView(APIView):
    def post(self, request, *args, **kwargs):
        refresh_token = request.query_params.get('refresh_token')
        salt = settings.SECRET_KEY
        payload = None
        msg = None

        try:
            payload = jwt.decode(refresh_token, salt, True)
        except jwt.exceptions.ExpiredSignatureError:
            return Response({'code': 1003, 'error': 'token已失效'})
        except jwt.DecodeError:
            return Response({'code': 1003, 'error': 'token认证失败'})
        except jwt.InvalidTokenError:
            return Response({'code': 1003, 'error': '非法的token'})

        username = payload['name']
        user_object = UserModel.objects.get(Q(username=username) | Q(mobile=username) | Q(email=username))
        access_token = create_access_token({'id': user_object.id, 'name': user_object.username})
        return Response({'code': 1000, 'msg': '刷新成功', 'access_token': access_token})


class UserViewSet(viewsets.ModelViewSet):
    queryset = UserModel.objects.all().order_by('id')
    serializer_class = UserModelSerializers
    authentication_classes = [AccessAuthentication, ]
